//app.js
//数据类型-字段
const data_type_strs = "Boolean Number String Function Array Date RegExp Object Error Symbol";
const class2type = {};
const toString = class2type.toString;
//extend
let extend = function () {
  var options, name, src, copy, copyIsArray, clone,
    target = arguments[0] || {},
    i = 1,
    length = arguments.length,
    deep = false;

  //--- extend(true||false,{},{}...)
  if (typeof target === "boolean") {
    deep = target;

    target = arguments[i] || {};

    i++;
  }

  //--- 第1个参数是bool值，target不是{}时
  if (typeof target !== "object" && target !== "function") {
    target = {};
  }

  //---
  for (; i < length; i++) {

    if ((options = arguments[i]) != null) {

      for (name in options) {
        src = target[name],
          copy = options[name];

        if (target === copy) {
          continue;
        }

        //--- 深复制
        if (deep && copy && (copy.constructor === Object || (copyIsArray = Array.isArray(copy)))) {
          if (copyIsArray) {
            copyIsArray = false;
            clone = src && Array.isArray(src) ? src : [];
          } else {
            clone = src && src.constructor === Object ? src : {};
          }

          target[name] = extend(deep, clone, copy);
        } else if (copy !== undefined) {
          target[name] = copy;
        }
      }
    }
  }

  return target;
};
//addZero
let addZero = function (num) {
  return num < 10 ? '0' + num : '' + num;
};
//
let dateFormat1 = function (str) {
  return str ? str.substr(0, 4) + '.' + str.substr(4, 2) + '.' + str.substr(6, 2) : ''
};
let dateFormat2 = function (str) {
  return str ? str.substr(0, 4) + '-' + str.substr(4, 2) + '-' + str.substr(6, 2) + ' ' + str.substr(8, 2) + ':' + str.substr(10, 2): ''
};
let dateFormat3 = function (str) {
  return str ? str.substr(0, 4) + '/' + str.substr(4, 2) + '/' + str.substr(6, 2) : ''
};
let dateFormatYMDHM = function (str) {
  return str ? str.substr(0, 4) + '/' + str.substr(4, 2) + '/' + str.substr(6, 2) + ' ' + str.substr(8, 2) + ':' + str.substr(10, 2) : ''
};
let dateStrFormat12 = function (dateStr) {
  if (dateStr) {
    let tmpStr = dateStr.replace(/[\-\:]+|\s+/g, "")
    //return tmpStr.length===8?tmpStr+"000000":tmpStr
    return tmpStr
  } else {
    return ""
  }
};
const util = require('./utils/util.js')
//
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    
  },
  onLoad: function () {
    
  },
  onReady: function () {

  },
  globalData: {
    /* need-animation */
    needAnimation: false,  //对应的页面容器的类名为bx-need_animation
    needAnimationLoad: false, //控制
    /* openAnimationLoad */
    setNeedAnimation(collectionName, collection, index) {
      // console.log(collectionName)
      // console.log(collection)
      if (this.data.needAnimationLoad) return Promise.reject()
      let tmpCollection = collection
      tmpCollection[index].openAnimationLoad = true
      this.setData({
        needAnimationLoad: true,
        needAnimation: true,
        [collectionName]: tmpCollection
      })
      return new Promise((resolve, reject) => {
        this.setData({
          needAnimationLoad: false
        })
        resolve()
        /* let timer = null
        clearTimeout(timer)
        timer = setTimeout(() => {
          let tmpCollection = collection
          tmpCollection[index].openAnimationLoad = false
          this.setData({
            needAnimationLoad: false,
            needAnimation: false,
            [collectionName]: tmpCollection
          })
          wx.nextTick(resolve)
        }, 500) */
      })
    },
    /* 
      setNeedAnimation: function(e){
        return app.globalData.setNeedAnimation.call(this,'menuData',e.currentTarget.dataset.index).then().catch()
      }
    */
    /* position */
    getLocation: function () {
      return new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'wgs84',
          success: res => {
            resolve(res)
          },
          fail: err => {
            wx.showModal({
              title: '提示',
              content: '获取当前位置信息失败',
              showCancel: false
            })
            reject()
          }
        })
      })
    },
    /* djs */
    djs: function(dataPropName,{
      initText = '获取验证码',
      time = 61,
      djsing = false
    }){
      this.setData({
        [`${dataPropName}.djsing`]:true
      })
      var initTime = time
      var timer = null
      return {
        startDjs:()=>{
          clearInterval(timer)
          timer = setInterval(()=>{
            let time = this.data[dataPropName].time
            if(time>=1){
              time--
              this.setData({
                [`${dataPropName}.initText`]:`( ${time}s )`,
                [`${dataPropName}.time`]:time
              })
            }else{
              time = initTime
              this.setData({
                [`${dataPropName}.initText`]:'获取验证码',
                [`${dataPropName}.time`]:initTime,
                [`${dataPropName}.djsing`]:false
              })
              console.log(this.data[dataPropName])
              clearInterval(timer)
            }
          },1000)
        },
        clearDjs:()=>{
          clearInterval(timer)
          this.setData({
            [`${dataPropName}.initText`]:'获取验证码',
            [`${dataPropName}.time`]:initTime,
            [`${dataPropName}.djsing`]:false
          })
        }
      }
    },
    /* common */
    toString: null,  //
    dataTypes: {},    //数据类型字段
    extend: extend,     //extend-fn
    addZero: addZero,   //
    dateFormat1: dateFormat1, //
    dateFormat2: dateFormat2, //
    dateFormat3: dateFormat3, //
    dateFormatYMDHM: dateFormatYMDHM, //
    dateStrFormat12: dateStrFormat12, //
    /*  */
    //Url: 'http://192.168.103.101:8080/car',  //请求地址
    Url:'https://sapp.csgxcf.com/car',
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    /* 请求返回结果token失效 */
    check_token: function(code){
      console.log(code)
      if(code==-2){
        wx.hideLoading()
        wx.showModal({
          title:'提示',
          content:'登录token已过期，请重新授权登录！',
          showCancel: false,
          success: res=>{
            if(res.confirm){
              //清除本地信息
              wx.clearStorageSync('userInfo_sj')
              //
              wx.navigateTo({
                url:'/pages/guide/guide'
              })
            }
          }
        })
        return true
      }
      return false
    },
    /* 获取缓存中的用户信息 */
    get_userInfo: function(){
      return wx.getStorageSync('userInfo_sj')
    },
    /* 判断是否已有用户手机号码 */
    has_user_phone: function(){
      let userInfo_sj = wx.getStorageSync('userInfo_sj')||{}
      if(!userInfo_sj.mobile){
        wx.showModal({
          title:'提示',
          content:'暂未绑定手机号码，请绑定',
          showCancel: false,
          confirmColor: app.globalData.modalConfirmColor,
          success: res=>{
            if(res.confirm){
              wx.switchTab({
                url:'/pages/personal/personal'
              })
            }
          }
        })
        return true
      }
      return false
    },
    /* Modal按钮文字颜色 */
    modalConfirmColor: '#5B9FFF'
  }
})